import * as _ from 'lodash';
import { Category } from '../categories/entities/category.entity';

export interface CategoryTreeNode {
  title: string;
  key: string;
  chain: string;
  children?: CategoryTreeNode[];
}

export default function getTree(list: Category[], result: CategoryTreeNode[] = [], index = 0, lastKeyString = '', lastChain = '') {
  const group = _.groupBy(list, (item) => item.tree.split('|')[index]);
  for (const key in group) {
    if (key === 'undefined') continue;
    const currentKeyIndex = result.length;
    const keyStr = lastKeyString ? [lastKeyString, currentKeyIndex].join('-') : String(currentKeyIndex);
    const chain = lastChain ? [lastChain, key].join('|') : String(key);
    const tempObject = {
      id: group[key][0].id,
      title: key,
      key: keyStr,
      chain: chain,
    };
    const children = getTree(group[key], [], index + 1, keyStr, chain);
    if (children.length) {
      tempObject['children'] = children;
    }
    result.push(tempObject);
  }
  return result;
}
